<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>更新管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form-model layout="inline" :model="form" :style="'margin-top:0px;'">
        <div>
          <a-form-model-item label="目标版本">
            <a-input v-model="form.versionLike" />
          </a-form-model-item>
          <a-form-model-item label="是否强更">
            <a-select v-model="form.isForceUpdate" :style="'width: 120px;'">
              <a-select-option value>请选择</a-select-option>
              <a-select-option :value="1">是</a-select-option>
              <a-select-option :value="0">否</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="更新时间">
            <a-range-picker @change="onChange">
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="shipCheck">查询</a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="shipPlus">+ 创建版本</a-button>
          </a-form-model-item>
        </div>
      </a-form-model>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        :style="'margin-top: 25px;'"
        :pagination="pagination"
        :row-key="record => record.id"
      >
        <!-- <template slot="versionContentList" slot-scope="record">
          <span
            v-for="(item,index) in record.versionContentList"
            :key="index"
          >{{index+1}}、{{item.content}}</span>
        </template>-->
        <span slot="do" slot-scope="record" :style="'display: flex; align-items: center;'">
          <a @click="edit(record)" style="margin-right:10px">编辑</a>
          <a @click="detail(record)">查看</a>
        </span>
      </a-table>
    </div>
    <!-- 创建 -->
    <a-modal
      v-model="visible"
      title="创建版本"
      :body-style="{padding:'24px 40px 0px 20px'}"
      :width="600"
      centered
      :confirmLoading="confirmStatus"
      @ok="addVersion"
      @cancel="cancelVersion"
    >
      <a-form-model
        ref="addForm"
        :rules="rules"
        :model="addForm"
        :label-col="{span:6}"
        :wrapper-col="{span:18}"
      >
        <a-row>
          <a-col :span="20">
            <!-- 系统 -->
            <a-form-model-item label="系统" prop="systemSign">
              <a-select v-model="addForm.systemSign">
                <a-select-option value>请选择</a-select-option>
                <a-select-option value="ANDROID">Android</a-select-option>
                <a-select-option value="IOS">iOS</a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 目标版本 -->
            <a-form-model-item label="目标版本" prop="version">
              <a-input type="text" v-model="addForm.version" />
            </a-form-model-item>
            <!-- 强制升级 -->
            <a-form-model-item label="强制升级" prop="isForceUpdate">
              <a-radio-group v-model="addForm.isForceUpdate">
                <a-radio :value="1">是</a-radio>
                <a-radio :value="0">否</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 应用下载地址 -->
            <a-form-model-item label="应用下载地址" prop="url">
              <a-input type="text" v-model="addForm.url" />
            </a-form-model-item>
            <!-- 更新时间 -->
            <a-form-model-item label="更新时间" prop="versionUpdateTime">
              <a-date-picker
                show-time
                :v-model="momentDate(addForm.versionUpdateTime)"
                @change="updateTime"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 版本特性 -->
        <a-row>
          <a-col :span="20">
            <a-form-model-item label="版本特性" prop="versionContent">
              <a-input type="text" v-model="addForm.versionContent" />
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-icon
              type="plus-circle"
              theme="filled"
              :style="'color:#1391FE;fontSize:20px;margin:10px 0 0 20px;'"
              @click="addPort"
            />
          </a-col>
        </a-row>
        <template v-if="(addForm.versionContentList.length)>0">
          <a-row v-for="(port,index) in addForm.versionContentList" :key="port.key">
            <a-col :span="20">
              <a-form-model-item
                :key="port.key"
                label="版本特性"
                :prop="'versionContentList.' + index + '.value'"
                :rules="{
                    required: true,
                    message: '必填项不能为空',
                    trigger: ['blur'],
                  }"
              >
                <a-input type="text" v-model="port.value" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4" :style="'margin-top: 10px;'">
              <a-icon
                type="plus-circle"
                theme="filled"
                :style="'color:#1391FE;fontSize:20px;margin:0 20px;'"
                @click="addPort"
              />
              <a-icon
                type="minus-circle"
                theme="filled"
                :style="'color:#EB5454;fontSize:20px;'"
                @click="removePort(port)"
              />
            </a-col>
          </a-row>
        </template>
      </a-form-model>
    </a-modal>
    <!-- 查看 -->
    <a-modal
      v-model="watchVisible"
      title="查看版本"
      :body-style="{padding:'24px 40px 0px 20px'}"
      :width="600"
      centered
      :footer="null"
      destroyOnClose
    >
      <a-form-model
        ref="detailForm"
        :model="detailForm"
        :label-col="{span:6}"
        :wrapper-col="{span:18}"
      >
        <a-row>
          <a-col :span="20">
            <!-- 系统 -->
            <a-form-model-item label="系统">
              <a-select v-model="detailForm.systemSign" disabled>
                <a-select-option value>请选择</a-select-option>
                <a-select-option value="ANDROID">Android</a-select-option>
                <a-select-option value="IOS">iOS</a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 目标版本 -->
            <a-form-model-item label="目标版本">
              <a-input type="text" v-model="detailForm.version" disabled />
            </a-form-model-item>
            <!-- 强制升级 -->
            <a-form-model-item label="强制升级">
              <a-radio-group v-model="detailForm.isForceUpdate" disabled>
                <a-radio :value="1">是</a-radio>
                <a-radio :value="0">否</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 应用下载地址 -->
            <a-form-model-item label="应用下载地址">
              <a-input type="text" v-model="detailForm.url" disabled />
            </a-form-model-item>
            <!-- 更新时间 -->
            <a-form-model-item label="更新时间">
              <a-date-picker
                show-time
                :default-value="momentDate(detailForm.versionUpdateTime, dateFormat)"
                :format="dateFormat"
                disabled
              />
            </a-form-model-item>
            <!-- 版本特性 -->
            <a-form-model-item
              v-for="(item,index) in detailForm.versionContentList"
              :key="index"
              label="版本特性"
            >
              <a-input type="text" v-model="item.content" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <!-- 编辑 -->
    <a-modal
      v-model="editVisible"
      title="修改版本"
      :body-style="{padding:'24px 40px 0px 20px'}"
      :width="600"
      centered
      @ok="editVersion"
      @cancel="cancelEdit"
      destroyOnClose
    >
      <a-form-model
        ref="editForm"
        :rules="rules"
        :model="editForm"
        :label-col="{span:6}"
        :wrapper-col="{span:18}"
      >
        <a-row>
          <a-col :span="20">
            <!-- 系统 -->
            <a-form-model-item label="系统" prop="systemSign">
              <a-select v-model="editForm.systemSign">
                <a-select-option value>请选择</a-select-option>
                <a-select-option value="ANDROID">Android</a-select-option>
                <a-select-option value="IOS">iOS</a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 目标版本 -->
            <a-form-model-item label="目标版本" prop="version">
              <a-input type="text" v-model="editForm.version" />
            </a-form-model-item>
            <!-- 强制升级 -->
            <a-form-model-item label="强制升级" prop="isForceUpdate">
              <a-radio-group v-model="editForm.isForceUpdate">
                <a-radio :value="1">是</a-radio>
                <a-radio :value="0">否</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- 应用下载地址 -->
            <a-form-model-item label="应用下载地址" prop="url">
              <a-input type="text" v-model="editForm.url" />
            </a-form-model-item>
            <!-- 更新时间 -->
            <a-form-model-item label="更新时间" prop="versionUpdateTime">
              <a-date-picker
                show-time
                :default-value="momentDate(editForm.versionUpdateTime, dateFormat)"
                :format="dateFormat"
                @change="editUpdateTime"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 版本特性 -->
        <a-row v-for="(item,index) in editForm.versionContentList" :key="index">
          <a-col :span="20">
            <a-form-model-item
              label="版本特性"
              :prop="'versionContentList.' + index + '.content'"
              :rules="{
                    required: true,
                    message: '必填项不能为空',
                    trigger: ['blur'],
                  }"
            >
              <a-input type="text" v-model="item.content" />
            </a-form-model-item>
          </a-col>
          <a-col :span="4" style="margin-top:10px">
            <a-icon
              type="plus-circle"
              theme="filled"
              :style="'color:#1391FE;fontSize:20px;margin:0 20px;'"
              @click="editAdd"
            />
            <a-icon
              v-if="index > 0"
              type="minus-circle"
              theme="filled"
              :style="'color:#EB5454;fontSize:20px;'"
              @click="removeEdit(item)"
            />
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import {
  queryVersionInfoList,
  addVersionInfo,
  getVersionInfoById,
  editVersionInfo
} from '@/api/appManage'
import moment from 'moment'

const fomrMessage = `必填项不能为空`
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '系统',
    customRender: (text, record, index) => {
      return record.systemSign === 'IOS' ? '苹果' : '安卓'
    }
  },
  {
    title: '目标版本',
    dataIndex: 'version'
  },
  {
    title: '强制更新',
    customRender: (text, record, index) => {
      return record.isForceUpdate ? '是' : '否'
    }
  },
  {
    title: '版本特性',
    // scopedSlots: {
    //   customRender: 'versionContentList'
    // },
    customRender: (text, record, index) => {
      let str = ''
      for (let i = 0; i < record.versionContentList.length; i++) {
        str += `${i + 1}、${record.versionContentList[i].content} `
      }
      return str
    },
    width: 320,
    ellipsis: true
  },
  {
    title: '更新时间',
    dataIndex: 'versionUpdateTime'
  },
  {
    title: '操作',
    key: 'do',
    scopedSlots: {
      customRender: 'do'
    }
  }
]
export default {
  data () {
    return {
      form: {
        versionLike: '', // 目标版本
        isForceUpdate: '', // 是否强制更新 0否1是
        startDate: '', // 开始日期
        endDate: '', // 结束日期
        productSign: 'SHIP_OWNER' // 产品标记类型 SHIP_OWNER(“船长”),DRIVER(“司机”)
      },
      pageNum: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns,
      pagination: {},
      visible: false,
      addForm: {
        productSign: 'SHIP_OWNER',
        systemSign: '',
        version: '',
        isForceUpdate: 0,
        url: '',
        versionUpdateTime: '',
        versionContentList: [],
        versionContent: ''
      },
      rules: {
        systemSign: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        version: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        isForceUpdate: [
          { required: true, message: fomrMessage, trigger: 'change' }
        ],
        url: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        versionUpdateTime: [
          { required: true, message: fomrMessage, trigger: ['change', 'blur'] }
        ],
        versionContent: [
          { required: true, message: fomrMessage, trigger: 'blur' }
        ]
      },
      dateFormat: 'YYYY-MM-DD HH:mm:ss',
      watchVisible: false,
      detailForm: {
        systemSign: '',
        version: '',
        isForceUpdate: '',
        url: '',
        versionUpdateTime: '',
        versionContentList: []
      },
      editVisible: false,
      editForm: {
        systemSign: '',
        version: '',
        isForceUpdate: '',
        url: '',
        versionUpdateTime: '',
        versionContentList: [],
        id: ''
      },
      btnControl: {},
      confirmStatus: false
    }
  },
  methods: {
    momentDate (date, format) {
      return moment(date)
    },
    addVersionRequest (e) {
      let _self = this
      _self.confirmStatus = true
      addVersionInfo(e)
        .then(res => {
          // console.log(res)
          if (res.code === 0) {
            _self.$message.success('创建成功！')
            _self.pageNum = 1
            _self.pageSize = 10
            _self.addForm.versionContentList = []
            _self.$refs['addForm'].resetFields()
            setTimeout(() => {
              _self.confirmStatus = false
              _self.visible = false
              _self.queryApp({
                ..._self.form,
                pageSize: _self.pageSize,
                pageNum: _self.pageNum
              })
            }, 500)
          }
        })
        .catch(rs => {
          _self.confirmStatus = false
        })
    },
    versionDetailRequest (e, modalType) {
      getVersionInfoById(e)
        .then(res => {
          if (modalType === 'detail') {
            this.watchVisible = true
            this.detailForm = { ...res.data }
          } else if (modalType === 'edit') {
            this.editVisible = true
            this.editForm = { ...res.data }
          }
        })
        .catch(rs => {})
    },
    versionEditRequest (e) {
      let _self = this
      editVersionInfo(e)
        .then(res => {
          if (res.code === 0) {
            _self.$message.success('修改成功！')
            _self.pageNum = 1
            _self.pageSize = 10
            setTimeout(() => {
              _self.editVisible = false
              _self.queryApp({
                ..._self.form,
                pageSize: _self.pageSize,
                pageNum: _self.pageNum
              })
            }, 500)
          }
        })
        .catch(rs => {})
    },
    shipCheck () {
      if (!this.btnControl.query) {
        this.$message.error('您无此权限！')
        return false
      }
      this.pageNum = 1
      let paramData = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...this.form
      }
      //   // console.log(paramData)
      this.queryApp(paramData)
    },
    shipPlus () {
      if (!this.btnControl.create) {
        this.$message.error('您无此权限！')
        return false
      }
      this.visible = true
    },
    queryApp (paramData) {
      this.loading = true
      queryVersionInfoList(paramData)
        .then(res => {
          // // console.log(res)
          this.data = res.data.list
          let currentPage = this.pageNum
          this.pagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.queryApp(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.queryApp(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => {})
    },
    onChange (data, dateString) {
      this.form.startDate = dateString[0]
      this.form.endDate = dateString[1]
    },
    edit (e) {
      if (!this.btnControl.edit) {
        this.$message.error('您无此权限！')
        return false
      }
      this.versionDetailRequest({ id: e.id }, 'edit')
    },
    detail (e) {
      if (!this.btnControl.query) {
        this.$message.error('您无此权限！')
        return false
      }
      // // console.log(e)
      this.versionDetailRequest({ id: e.id }, 'detail')
    },
    updateTime (date, dateString) {
      this.addForm.versionUpdateTime = dateString
    },
    addVersion () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // console.log(this.addForm)
          let contentList = []
          let targetList = this.addForm.versionContentList
          contentList[0] = {
            content: this.addForm.versionContent
          }
          for (let i = 0; i < targetList.length; i++) {
            contentList.push({
              content: targetList[i].value
            })
          }
          delete this.addForm.versionContent
          delete this.addForm.versionContentList
          this.addVersionRequest({
            ...this.addForm,
            versionContentList: contentList
          })
        }
      })
    },
    cancelVersion () {
      this.addForm.versionContentList = []
      this.$refs['addForm'].resetFields()
    },
    addPort () {
      this.addForm.versionContentList.push({
        value: '',
        key: Date.now()
      })
    },
    removePort (e) {
      let index = this.addForm.versionContentList.indexOf(e)
      if (index !== -1) {
        this.addForm.versionContentList.splice(index, 1)
      }
    },
    editUpdateTime (date, dateString) {
      this.editForm.versionUpdateTime = dateString
    },
    editVersion () {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // console.log(this.editForm)
          let contentList = []
          let targetList = this.editForm.versionContentList
          for (let i = 0; i < targetList.length; i++) {
            contentList.push({
              content: targetList[i].content
            })
          }
          delete this.editForm.versionContentList
          this.versionEditRequest({
            ...this.editForm,
            'versionContentList': contentList
          })
        }
      })
    },
    cancelEdit () {},
    editAdd () {
      this.editForm.versionContentList.push({
        content: '',
        key: Date.now()
      })
    },
    removeEdit (e) {
      let index = this.editForm.versionContentList.indexOf(e)
      if (index !== -1) {
        this.editForm.versionContentList.splice(index, 1)
      }
    }
  },
  mounted () {
    this.queryApp({
      ...this.form,
      pageSize: this.pageSize,
      pageNum: this.pageNum
    })
    this.$nextTick(() => {
      this.btnControl = this.$root._bc
      // console.log(this.$root._bc)
    })
  }
}
</script>
<style lang="less" scoped>
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;
}
</style>
